const BASE_URL = 'http://localhost:8082'
export const myRequest = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      success: (res) => {
        if (res.data.status !== 0) {
          return uni.showToast({
            title: '获取数据失败'
          })
        }
        resolve(res)
      },
      fail: (err) => {
        uni.showToast({
          title: '请求接口失败'
        })
        reject(err)
      }
    })
  })
}


export default (url, data = {}, method = 'GET') => {
  return new Promise((resolve, reject) => {
    // 1. new Promise初始化promise实例的状态为pending
    wx.request({
      url: config.host + url,
      data,
      method,
      header: {
        cookie: wx.getStorageSync('cookies') ? wx.getStorageSync('cookies').find(item => item.indexOf('MUSIC_U') !== -1) : ''
      },
      success: (res) => {
        // console.log('请求成功: ', res);
        if (data.isLogin) {// 登录请求
          // 将用户的cookie存入至本地
          wx.setStorage({
            key: 'cookies',
            data: res.cookies
          })
        }
        resolve(res.data); // resolve修改promise的状态为成功状态resolved
      },
      fail: (err) => {
        // console.log('请求失败: ', err);
        reject(err); // reject修改promise的状态为失败状态 rejected
      }
    })
  })

}




//同时发送异步代码的次数
let ajaxTimes = 0;


export default (params) => {
  ajaxTimes++
  wx.showLoading({
    title: '加载中',
  })
  const baseUrl = "接口报错"
  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      url: baseUrl + params.url,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        ajaxTimes--
        if (ajaxTimes === 0) {
          wx.hideLoading()
        }
      }
    });
  });
}






let ajaxTime = 0;
const baseURL = 'http://157.122.54.189:9088';
export default (params) => {
  ajaxTime++;
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      url: baseURL + params.url,
      success(res) {
        if (res.data.code) {
          uni.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        } else {
          resolve(res.data)
        }
      },
      fail(err) {
        reject(err)
      },
      complete() {
        ajaxTime--;
        if (!ajaxTime) {
          uni.hideLoading()
        }
      }
    })
  })
}






Vue.filter('formatDate', (date) => {
  const nDate = new Date(date)
  const year = nDate.getFullYear()
  const month = nDate.getMonth().toString().padStart(2, 0)
  const day = nDate.getDay().toString().padStart(2, 0)
  return year + '-' + month + '-' + day
})